#ifndef __CFG__H_
#define __CFG__H_

#include <stdint.h>

#include "usart.h"

#define BUFFER_SIZE 128
#define RX_BUFFER_SIZE 128
#define CMD_TIMEOUT_MS 100

typedef enum {
    ILLEGAL_FUNC = 0X1,
    ILLEGAL_ADDRESS = 0X2,
    ILLEGAL_DATA = 0X3,
    DEVICE_ERR = 0X4,
    DEVICE_ACKING = 0X5,
    DEVICE_BUSY = 0X6,
    CRC_ERR = 0x07,
    UNKNOW_ERR = 0x08,
} ERROR_CODE;

typedef enum {
    RS485_MODE = 0,
    TCP_MODE = 1,
} DEV_COM_MODE;

typedef enum {
    TCP_SRV_MODE = 0,
    TCP_CLI_MODE = 1,
} COM_TCP_MODE;

typedef enum {
    MANUAL_MODE = 0,
    AUTO_MODE = 1,
} DEV_CTRL_MODE;

#pragma pack(1)
typedef struct {
    uint8_t com_mode;
    uint8_t com_tcp_mode;
    uint8_t ctrl_mode;
    uint8_t channel_value;
    uint8_t rs485_id;
    uint32_t rs485_buad;
    uint8_t poll_time[8];
    uint8_t ip[4];
    uint16_t port;
    uint8_t dest_ip[4];
    uint16_t dest_port;
    uint8_t need_ota; 
    uint16_t crc_valid;
} dev_cfg_t;
#pragma pack()

typedef struct {
    uint8_t cmdHeader[4];          // 命令头 (4 bytes)
    uint8_t address;               // 地址 (1 byte)
    uint16_t functionCode;         // 功能码 (2 bytes)
    uint16_t dataLength;           // 数据长度 (2 bytes)
    uint8_t data[RX_BUFFER_SIZE];  // 数据
    uint16_t checksum;             // CRC16 校验 (2 bytes)
} ProtocolFrame_t;

typedef void (*dev_send_ack)(uint8_t *data, uint16_t length, int index);

uint16_t CRC16_Calculate(uint8_t *data, uint16_t length);
void load_local_cfg(void);
extern dev_cfg_t cfg;

void TimerCallback(void const *argument);
void cmd_process_detail(uint8_t *localBuffer, uint16_t localLength,
                        dev_send_ack cb, int index);
#endif
